package com.cmwa.solution.business.product.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.cmwa.solution.base.controller.BaseController;
import com.cmwa.solution.base.entity.Page;
import com.cmwa.solution.base.entity.Result;
import com.cmwa.solution.base.entity.SearchParam;
import com.cmwa.solution.business.archiveManagement.service.ArchiveManagementService;
import com.cmwa.solution.business.product.entity.SubPrdLineVo;
import com.cmwa.solution.business.product.entity.TreFeeDetailVo;
import com.cmwa.solution.business.product.service.SubPrdLineService;
import com.cmwa.solution.business.product.service.TreFeeTypeService;
import com.cmwa.solution.business.product.service.TreNavBizService;
import com.cmwa.solution.business.treYield.entity.TreYieldVo;
import com.cmwa.solution.business.treYield.service.TreYieldService;
import com.cmwa.solution.sys.attach.entity.AttachVo;
import com.cmwa.solution.sys.attach.service.AttachService;
import com.cmwa.solution.sys.msg.util.StringUtil;
import com.cmwa.solution.utils.cached.DictionaryCached;
import com.google.common.base.Joiner;

import net.sf.json.JSONArray;



/**
 * 招商财富产品表控制器
 * 
 * @author ex-zhengqq
 * @date 2019-01-22 15:33:47
 */
@Controller
@RequestMapping("/business/product")
public class SubProductLineController extends BaseController {

	private final static String JSP_PATH = "business/product/";
	@Resource
	private SubPrdLineService subPrdLineService;
	
	@Resource
	private TreFeeTypeService prdFeeService;
		
	@Resource
	private AttachService attachService;
	
	@Resource
	private TreNavBizService treNavBizService;
	
	@Resource
	private TreYieldService treYieldService; 
	
	@Resource
	private ArchiveManagementService archiveManagementService;
	
	@RequestMapping("/home")
	public String home(@RequestParam(value="reSource",required=false)String reSource,@RequestParam(value="prdFlag",required=false)String prdFlag,ModelMap model) {
		model.addAttribute("reSource", reSource);
		model.addAttribute("prdFlag", prdFlag);
		return JSP_PATH+"home";
	}
	
	/**
	 * 跳转到列表页面
	 * @author ex-zhengqq
	 * @date 2019-01-22 15:33:47
	 * @param model
	 * @return
	 */
	@RequestMapping("/prdInfoListView")
	public String prdInfoListView(@RequestParam(value="reSource",required=false)String reSource,@RequestParam(value="prdFlag",required=false)String prdFlag,ModelMap model) {
		List<?> prdTypeList = DictionaryCached.getDictionaryByType("PRD_CATEGORY", "PRD_CATEGORY", "PRD_CATEGORY");
		List<?> prdTermList = DictionaryCached.getDictionaryByType("PRD_TERM", "PRD_TERM", "PRD_TERM");
		List<?> riskLevelList = DictionaryCached.getDictionaryByType("RISK_LEVEL", "RISK_LEVEL", "RISK_LEVEL");

		model.addAttribute("prdFlag", prdFlag);
		model.addAttribute("prdTypeList", prdTypeList);
		model.addAttribute("prdTermList", prdTermList);
		model.addAttribute("riskLevelList", riskLevelList);
		model.addAttribute("reSource", reSource);
		
		return JSP_PATH + "prdInfoList";
	}
	
	/**
	 * 分页查询
	 * @param param
	 * @return
	 */
	@RequestMapping("/prdInfoListPage")
	@ResponseBody
	public Page<SubPrdLineVo> prdInfoListPage(SearchParam param) {
		Page<SubPrdLineVo> list = subPrdLineService.prdInfoListPage(param);
		return list;
	}
	
	@RequestMapping("/addPrdInfo")
	public String addView(Model model) {
		//开放频率
		List<?> openFrequencyDicts = DictionaryCached.getDictionaryByType("OPEN_FREQUENCY");
		List<?> prdFlags = DictionaryCached.getDictionaryByType("PRD_LINE_FLAG", "PRD_LINE_FLAG", "PRD_LINE_FLAG");
		//产品收益分配 
		List<?> yieldAllotTypeList = DictionaryCached.getDictionaryByType("YIELD_PAY_RATE", "YIELD_PAY_RATE", "YIELD_PAY_RATE");
				
		model.addAttribute("prdFlags", prdFlags);
		model.addAttribute("openFrequencyDicts", openFrequencyDicts);
		model.addAttribute("yieldAllotTypeList", yieldAllotTypeList);
		return JSP_PATH + "addPrdInfo";
	}
	

	/**
	 * 新增
	 * @return
	 */
	@RequestMapping("/savePrdInfo")
	public String savePrdInfo(SubPrdLineVo subPrdLineVo) {
		subPrdLineService.savePrdInfo(subPrdLineVo, subPrdLineVo.getAttIds());
		return redirectSuccess();
	}
	
	/**
	 * 根据不同的参数跳转页面
	 * detail :详情页
	 * @param model
	 * @return
	 */
	@RequestMapping("/goPrdInfoPage")
	public String goPrdInfoPage(@RequestParam("method") String method,
								@RequestParam("subPrdCode") String subPrdCode,ModelMap model) {
		String goPage = "";
		SubPrdLineVo prdInfoVo = subPrdLineService.getPrdInfoByCode(subPrdCode);
		model.put("prdInfoVo", prdInfoVo);
		//费用
	    List<TreFeeDetailVo> prdFees = prdFeeService.prdFeeInfoByCode(subPrdCode);
	    // 收益率
	    TreYieldVo treYieldVo = treYieldService.findYieldByCode(subPrdCode);//查询产品收益率
	    model.put("treYieldVo", treYieldVo);
	    model.put("prdFees", prdFees);
		if(StringUtils.equals(method, "detail")){
			goPage = "prdInfoDetail";
		}
		List<AttachVo> attachVos = attachService.queryAttachByRelIdAndType(subPrdCode, "PRD_LINE");
		model.addAttribute("attachVos", attachVos);
		return JSP_PATH + goPage;
	}
	
	@ResponseBody
	@RequestMapping("/navData")
	public Result<Object> navData(@RequestParam("subPrdCode") String subPrdCode,
			@RequestParam("limit") String limit) {
	    Result<Object> result = new Result<>();
	    result.setSuccess(true);
		// 净值
	    List<Map<String,Object>> navs = treNavBizService.navBizInfoByCode(subPrdCode,limit);
	    result.setObject(JSONArray.fromObject(navs));
		return result;
	}
	
	
	/**
	 * 导出
	 * @param sp
	 * @return
	 */
	@RequestMapping("/prdInfoExportTo")
	public void prdInfoExportTo(SearchParam sp, HttpServletResponse response) throws IOException{
		//获取当前操作人
		//sp.getSp().put("currUserId", SessionUtils.getEmployee().getID());
		subPrdLineService.export(response, sp);
	}
	
	@ResponseBody
	@RequestMapping("/attachmentListPage")
	public Page<AttachVo> attachmentListPage(SearchParam param){
		Page<AttachVo> list = archiveManagementService.archiveManagementListPage(param);
		return list;
	}
	
	/**
	 * 前往选择产品页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/selectProductView")
	public String selectProductView(ModelMap model) {
		return "business/common/selectProductView";
	}
	
	
	/**
	 * 保存附件
	 * @param documentVo
	 * @return
	 */
	@RequestMapping("/saveAttaches")
	public String saveAttaches(SubPrdLineVo subPrdLineVo){
		
		String subPrdCode = subPrdLineVo.getSubPrdCode();
		if(StringUtils.isNotBlank(subPrdCode)){//保存附件关联关系表
			subPrdLineService.updateAttachRel(subPrdLineVo,"PRD_DEMAND");
		}
		return redirectSuccess();
	}
	/**
	 * 获取热销产品
	 * @param model
	 * @return
	 */
	@RequestMapping("/getSellWellPrd")
	@ResponseBody
	public String getSellWellPrd(ModelMap model){
		List<SubPrdLineVo> prdInfoVo = subPrdLineService.getSellWellPrd(2);
		String sellWellPrd2Json = JSONArray.fromObject(prdInfoVo).toString();
		return sellWellPrd2Json;
	}
	
	@RequestMapping("/updateView")
	public String updateView(@RequestParam(value="subPrdCode") String subPrdCode,ModelMap model) {
		SubPrdLineVo prdInfoVo = subPrdLineService.getPrdInfoByCode(subPrdCode);
		List<?> openFrequencyDicts = DictionaryCached.getDictionaryByType("OPEN_FREQUENCY");
		//产品收益分配 
		List<?> yieldAllotTypeList = DictionaryCached.getDictionaryByType("YIELD_PAY_RATE", "YIELD_PAY_RATE", "YIELD_PAY_RATE");
				
		model.put("prdInfoVo", prdInfoVo);
		model.put("openFrequencyDicts", openFrequencyDicts);
		model.put("yieldAllotTypeList", yieldAllotTypeList);
		List<?> prdFlags = DictionaryCached.getDictionaryByType("PRD_LINE_FLAG", "PRD_LINE_FLAG", "PRD_LINE_FLAG");
		model.addAttribute("prdFlags", prdFlags);
		String archive2Json = "";
		//加载附件信息
		List<AttachVo> attaches = attachService.queryAttachByRelIdAndType(subPrdCode, "PRD_LINE");
		//如果附件信息不为空，则加载附件信息
		if(null != attaches) {
			archive2Json = StringUtil.changeSpecialCharacter(JSONArray.fromObject(attaches).toString());
		}
		model.addAttribute("attachList", archive2Json);
		return JSP_PATH+"updatePrdInfo";
	}
	
	/**
	 * 修改
	 * @return
	 */
	@RequestMapping("/updatePrdInfo")
	public String updatePrdInfo(SubPrdLineVo prdInfoVo) {
		subPrdLineService.updatePrdInfo(prdInfoVo, prdInfoVo.getAttIds());
		return redirectSuccess();
	}
	
	@ResponseBody
	@RequestMapping("/delete")
	public Result<SubPrdLineVo> delete(@RequestParam("subPrdCode")String subPrdCode) {
		Result<SubPrdLineVo> result = new Result<SubPrdLineVo>();
		result.setSuccess(true);
		result.setMessage("删除成功");
		try {
			subPrdLineService.deletePrdLineByCode(subPrdCode);
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("删除失败");
		}
		return result;
	}
	
	/**
	 * 打包下载附件
	 * @param id
	 * @throws IOException 
	 */
	@RequestMapping("/download")
	public void download(@RequestParam("subPrdCode")String subPrdCode, HttpServletResponse response, HttpServletRequest request) throws IOException {
		SubPrdLineVo prdInfoVo = subPrdLineService.getPrdInfoByCode(subPrdCode);
		List<AttachVo> attachVos = attachService.queryAttachByRelIdAndType(subPrdCode, "PRD_LINE");
		String fileName = "招商财富产品线";
		if (prdInfoVo != null ) {
			fileName = prdInfoVo.getSubFundSname();
		}
		
		if (prdInfoVo != null && CollectionUtils.isNotEmpty(attachVos)) {
			List<String> attIds = new ArrayList<>();
			for (AttachVo attach : attachVos) {
				attIds.add(attach.getAttId());
			}
			attachService.downloadAttachZip(Joiner.on(",").join(attIds), fileName, request, response);
		} else {
			attachService.downloadAttachZip("", fileName, request, response);
		}
	}
	
	@ResponseBody
	@RequestMapping("/isRepeat")
	public Result<SubPrdLineVo> isRepeat(@RequestParam(value="subPrdCode",required=false)String subPrdCode,
			@RequestParam("subFundSname") String subFundSname) {
		Result<SubPrdLineVo> result = new Result<SubPrdLineVo>();
		result.setMessage("查询成功");
		try {
			result.setSuccess(!subPrdLineService.isRepeat(subPrdCode,subFundSname));
		} catch (Exception e) {
			result.setSuccess(false);
			result.setMessage("查询失败");
		}
		return result;
	}
}
